package com.goldcn.sys.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import com.goldcn.interceptor.CurrentUser;
import com.goldcn.common.*;
import com.goldcn.config.PropertiesConfig;
import com.goldcn.sys.dao.GcnSysPageMapper;
import com.goldcn.sys.dao.GcnSysRoleMapper;
import com.goldcn.sys.dao.GcnSysUserMapper;
import com.goldcn.sys.dao.GcnSysUserRoleMapper;
import com.goldcn.sys.model.*;
import com.goldcn.sys.model.util.*;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.MapUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Component
public class SysRoleService {
	@Autowired
	GcnSysRoleMapper gcnSysRoleMapper;
	@Autowired
	GcnSysPageMapper gcnSysPageMapper;
	@Autowired
	GcnSysUserMapper sysUserMapper;
	@Autowired
	GcnSysUserRoleMapper sysUserRoleMapper;
	@Autowired
	SysUserRoleService sysUserRoleService;
	@Autowired
	SysPageService sysPageService;
	@Autowired
	SysRolePageFunctionService sysRolePageFunctionService;
	@Autowired
	PropertiesConfig propertiesConfig;


	public GcnSysRole selectByPrimaryKey(String roleID){
		return gcnSysRoleMapper.selectByPrimaryKey(roleID);
	}

	public List<GcnSysRole> selectAll(){
		return gcnSysRoleMapper.selectAll();
	}

	public boolean delete(String id){
		int roleUserNum = sysUserRoleService.selectPageNumByCondition(id);
		if(roleUserNum > 0){
			return false;
		}
		GcnSysRole sysRole = gcnSysRoleMapper.selectByPrimaryKey(id);
		sysRole.setIsStop(StatusEnum.STOPED.value());
		int f = gcnSysRoleMapper.updateByPrimaryKey(sysRole);
		return f > 0;
	}

	/**
	 *
	 * @param param
     * @return
     */
	public String page(Map<String,String> param){
		//分页
		int pageIndex = Integer.parseInt(param.get("pageIndex"))+1;
		int pageSize = Integer.parseInt(param.get("pageSize"));
		//字段排序
		String sortField = param.get("sortField");
		String sortOrder = param.get("sortOrder");
		MiniuiPage miniPage = MiniuiPage.getPageInfo(pageIndex,pageSize,sortField,sortOrder,"updateTime DESC");
		PageHelper.startPage(miniPage.getPageIndex(),miniPage.getPageSize(),true);
		PageHelper.orderBy(miniPage.getOrderBy());
		Page page=(Page)gcnSysRoleMapper.selectAllAsMap();
		long total = page.getTotal();
		List<GcnSysRole> list = page.getResult();
		return new Result(list).put("total",total).returnSuccess();
	}

	/**
	 * 查询角色信息
	 * @param roleID
	 * @return
	 */
	public Object findRole(String roleID){
		GcnSysRole sysRole=null;
		if(Strings.isNotBlank(roleID)){
			sysRole = gcnSysRoleMapper.selectByPrimaryKey(roleID);
		}
		List<Map<String,String>> sysPages = sysPageService.getAllAndHasRole(roleID);
		Map<String,Object> map = Maps.newHashMap();
		map.put("sysRole",sysRole);
		map.put("sysPages",sysPages);
		ResultData resultData = new ResultData(map);
		resultData.setData(map);
		return map;
	}


	/**
	 * 获取用户功能模块权限
	 * @param userID
	 * @return
     */
	public Object userPermissions(String userID){
		List<String> roleIds = sysUserRoleMapper.getUserRoleIds(userID);//用户角色
		List<String> rolePages = new ArrayList();
		if(null != roleIds && roleIds.size() != 0){
		 	rolePages = sysRolePageFunctionService.getUserRolePage(roleIds);//用户功能模块权限
		}
		Object  sysPages =  sysPageService.getAll(new HashMap<String, String>());
		ResultData resultData = new ResultData();
		Map map = new HashMap();
		map.put("rolesPages",rolePages);
		map.put("sysPages",sysPages);
		//resultData.setData(map);
		return map;
	}

	private List<String> getUserRoles(String userID){
		List<String> _roles = new ArrayList<String>();
		List<Map<String,String>> sysRoleList = sysUserMapper.findUserRoles(userID);
		if(sysRoleList == null || sysRoleList.size() == 0){
			return Lists.newArrayList();
		}
		String roleId="";
		for(int i=0;i<sysRoleList.size();i++){
			roleId =sysRoleList.get(i).get("roleID");
			_roles.add(roleId);
		}
		return _roles;
	}

	/**
	 * 新增或修改角色
	 * @param role
	 * @param sysUser
	 */
	@Transactional
	public GcnSysRole saveOrUpdateRoles(Map role, CurrentUser sysUser){
		GcnSysRole sysRole = null;
		if(StringUtil.isNotEmpty((String)role.get("roleID"))){
			sysRole = gcnSysRoleMapper.selectByPrimaryKey((String)role.get("roleID"));
			sysRole.setRoleName((String)role.get("roleName"));
			sysRole.setRemark((String)role.get("remark"));
			sysRole.setUpdateUser(sysUser.getUserID());
			sysRole.setUpdateTime(System.currentTimeMillis());
			gcnSysRoleMapper.updateByPrimaryKeySelective(sysRole);
		}else{
			sysRole = new GcnSysRole();
			sysRole.setRoleID(CommonUtils.getGUID());
			sysRole.setRoleName((String)role.get("roleName"));
			sysRole.setRemark((String)role.get("remark"));
			sysRole.setAddUser(sysUser.getUserID());
			sysRole.setAddTime(System.currentTimeMillis());
			sysRole.setUpdateUser(sysUser.getUserID());
			sysRole.setUpdateTime(System.currentTimeMillis());
			gcnSysRoleMapper.insertSelective(sysRole);
		}
		return sysRole;
	}

	@Transactional
	public ResultData saveOrUpdateRole(Map role, List<String> pages, CurrentUser sysUser){
		GcnSysRole sysRole = saveOrUpdateRoles(role,sysUser);
		//数据权限
		String roleID = MapUtils.getString(role,"roleID","");

		if(StringUtil.isNotEmpty(roleID)){
			sysRolePageFunctionService.deleteByRoleID(roleID);//删除原有权限
		}

		List<GcnSysRolePageFunction> list = Lists.newArrayList();
		for(String pageID : pages){
			GcnSysRolePageFunction page = new GcnSysRolePageFunction();
			page.setID(CommonUtils.getGUID());
			page.setPageID(pageID);
			page.setRoleID(sysRole.getRoleID());
			page.setAddTime(System.currentTimeMillis());
			page.setAddUser(sysUser.getUserID());
			page.setUpdateTime(System.currentTimeMillis());
			page.setUpdateUser(sysUser.getUserID());
			list.add(page);
		}
		if(list.size() != 0){
			sysRolePageFunctionService.insertBatch(list);
		}
		return  new ResultData();
	}

	public Map<String,Object> getRoleUsers(String roleID) {
		GcnSysRole sysRole = gcnSysRoleMapper.selectByPrimaryKey(roleID);
		List<GcnSysUser> relatedUsers = sysUserMapper.findRelatedUser(roleID);
		List<GcnSysUser> unRelatedUsers = sysUserMapper.findUnRelatedUser(roleID);
		Map<String, Object> map = new HashMap();
		map.put("relatedUsers", relatedUsers);
		map.put("unRelatedUsers", unRelatedUsers);
		map.put("sysRole",sysRole);
		return map;
	}

	/**
	 * 查询角色关联和未关联用户
	 * @param roleID
	 * @return
	 */
	public ResultData<Object> getRoleUsersResult(String roleID) {
		Map<String,Object> roleUsers = getRoleUsers(roleID);
		return new ResultData<Object>(BaseCode.SUCCESS_CODE,roleUsers);
	}

	/**
	 * 保存角色关联用户
	 * @param roleID
	 * @param list
	 * @param user
	 */
	@Transactional
	public void saveRoleUsers(String roleID, List<Map> list, CurrentUser user){
		sysUserRoleMapper.deleteByRoleId(roleID);
		for(Map sysUser : list){
			GcnSysUserRole sysUserRole = new GcnSysUserRole();
			sysUserRole.setID(CommonUtils.getGUID());
			sysUserRole.setRoleID(roleID);
			sysUserRole.setUserID((String) sysUser.get("userID"));
			sysUserRole.setAddUser(user.getUserID());
			sysUserRole.setAddTime(System.currentTimeMillis());
			sysUserRoleMapper.insertSelective(sysUserRole);
		}
	}
}
